package bootstrap

import (
	"github.com/robfig/cron/v3"
	log "github.com/sirupsen/logrus"
	"go.uber.org/zap"
	"mall-portalv2/global"
	"mall-portalv2/internal/model"
	"time"
)

/**
* Author: joker
* TODO: test
* Date: 2022/8/25
* Time: 下午1:44
**/

type Job struct {
	Shut chan int `json:"shut"`
}

func InitWechatCron() {
	job := Job{
		Shut: make(chan int, 1),
	}
	job.Run()
	go StartJob("0 0 4 * * *", job)
	//go StartJob("*/4 * * * * *", job)
}

func (j *Job) Run() {
	// TODO: 检查一下15天到了的记录给他改成15天已自动确认收货
	t1 := time.Now().Year()  //年
	t2 := time.Now().Month() //月
	t3 := time.Now().Day()   //日
	nowTime := time.Date(t1, t2, t3, 0, 0, 0, 0, time.Local)
	sub15Time := nowTime.AddDate(0, 0, -15).Format("2006-01-02")
	global.Log.Info("测试cron", zap.Any("打印当前时间", nowTime), zap.Any("sub15Time", sub15Time))
	tb := model.OmsOrder{}
	updates := make(map[string]interface{})
	updates["status"] = 3
	if err := global.DB.Table(tb.TableName()).Where("DATE_FORMAT(delivery_time,'%Y-%m-%d') <= DATE_FORMAT('" + sub15Time + "','%Y-%m-%d')").Updates(updates).Error; err != nil {
		global.Log.Error("修改订单为自动收货失败", zap.Error(err))
		return
	}
	global.Log.Info("修改订单为自动收货成功")
}

func StartJob(spec string, job Job) {
	logger := &CLog{clog: log.New()}
	logger.clog.SetFormatter(&log.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05",
	})
	c := cron.New(cron.WithSeconds())

	c.AddJob(spec, &job)

	// 启动执行任务
	c.Start()
	// 退出时关闭计划任务
	defer c.Stop()

	// 如果使用 select{} 那么就一直会循环
	select {
	case <-job.Shut:
		return
	}
}

func StopJob(shut chan int) {
	shut <- 0
}

type CLog struct {
	clog *log.Logger
}

func (l *CLog) Info(msg string, keysAndValues ...interface{}) {
	l.clog.WithFields(log.Fields{
		"data": keysAndValues,
	}).Info(msg)
}

func (l *CLog) Error(err error, msg string, keysAndValues ...interface{}) {
	l.clog.WithFields(log.Fields{
		"msg":  msg,
		"data": keysAndValues,
	}).Warn(msg)
}
